package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.exception.ServiceException;
import com.zzyl.nursing.service.WechatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
@Slf4j
public class WechatServiceImpl implements WechatService {

    /**
     * 获取openid接口地址
     */
    private static final String OPEN_ID_URL = "https://api.weixin.qq.com/sns/jscode2session";

    /**
     * 获取access_token接口地址
     */
    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";

    /**
     * 获取手机号码接口地址
     */
    private static final String PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token={}";

    @Value("${wechat.appId}")
    private String appId;

    @Value("${wechat.appSecret}")
    private String appSecret;

    /**
     * 获取openId
     *
     * @param code
     * @return
     */
    @Override
    public String getOpenId(String code) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("appid", appId);
        paramMap.put("secret", appSecret);
        paramMap.put("js_code", code);
        paramMap.put("grant_type", "authorization_code");

        HttpResponse res = HttpRequest.get(OPEN_ID_URL).form(paramMap).timeout(5000).execute();
        if(res.isOk()) {
            String result = res.body();
            log.info("获取openId: {}", result);
            //解析json对象
            JSONObject jsonObject = JSONUtil.parseObj(result);
            String openid = jsonObject.getStr("openid");
            //如果为空，说明出错了，微信报错信息里才拿不到openid，这时需要看上面 记录的日志信息
            if(StrUtil.isNotBlank(openid)) {
                return openid;
            }
        }
        throw new ServiceException("获取openId失败，请稍后重试");
    }

    /**
     * 获取手机号码
     *
     * @param phoneCode
     * @return
     */
    @Override
    public String getPhone(String phoneCode) {

        String accessToken = getAccessToken();
        String url = StrUtil.format(PHONE_URL, accessToken);
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("code", phoneCode);
        HttpResponse res = HttpRequest.post(url).body(JSONUtil.toJsonStr(paramMap)).timeout(5000).execute();
        if(res.isOk()) {
            String result = res.body();
            log.info("获取手机号: {}", result);
            //解析json对象
            JSONObject jsonObject = JSONUtil.parseObj(result);
            String phoneNumber = jsonObject.getJSONObject("phone_info").getStr("phoneNumber");
            //如果为空，说明出错了，微信报错信息里才拿不到openid，这时需要看上面 记录的日志信息
            if(StrUtil.isNotBlank(phoneNumber)) {
                return phoneNumber;
            }
        }
        throw new ServiceException("获取手机号失败，请稍后重试");
    }

    private String getAccessToken(){
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("appid", appId);
        paramMap.put("secret", appSecret);
        paramMap.put("grant_type", "client_credential");
        HttpResponse res = HttpRequest.get(ACCESS_TOKEN_URL).form(paramMap).timeout(5000).execute();
        if(res.isOk()) {
            String result = res.body();
            log.info("获取access_token: {}", result);
            //解析json对象
            JSONObject jsonObject = JSONUtil.parseObj(result);
            String access_token = jsonObject.getStr("access_token");
            //如果为空，说明出错了，微信报错信息里才拿不到openid，这时需要看上面 记录的日志信息
            if(StrUtil.isNotBlank(access_token)) {
                return access_token;
            }
        }
        throw new ServiceException("获取access_token失败，请稍后重试");
    }
}
